"""
@version: python3.9
@project:selenium
@file:   Logs.py
@date:   2021/8/18 19:13
@Author: jia
@Desc:  公共日志配置
日志级别：DEBUG < INFO < WARNING < ERROR < CRITICAL(崩溃的错误)
当日志设置为最高级别CRITICAL时，低级别信息都不再打印
当日志设置为最低级别DEBUG时，所有信息都打印
"""

import os
import logging
import logging.config
import time

"""不同的项目要修改项目名称"""
project_name = 'DataCrawler'


class Logs:
    def __init__(self):
        """定义时间格式"""
        local = time.localtime()
        now_time = time.strftime('%Y_%m_%d_%H_%M@', local)

        """定义项目根目录"""
        abs_path = os.path.abspath(project_name)
        path1 = abs_path.split(project_name)
        project_path = [path1[0], project_name]

        """定义日志目录"""
        log_dir = ''.join(project_path) + r'\Logs'
        print(f'log_dir:{log_dir}')

        # """定义日志路径, \为转义符 双\\使反斜杠成为普通字符\"""
        self.debug_log = os.path.join(log_dir + '\\' + now_time + 'debug.log')

        """日志目录为空时创建目录"""
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

    def _conf(self):
        """日志的配置文件"""

        config = {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "simple": {
                    'format': '%(asctime)s [%(filename)s:%(lineno)d] [%(levelname)s]- %(message)s'
                },
                'standard': {
                    'format': '%(asctime)s [%(threadName)s:%(thread)d] '
                              '[%(filename)s:%(lineno)d] [%(levelname)s]- %(message)s'
                },
            },
            "handlers": {
                "console": {
                    "class": "logging.StreamHandler",
                    "level": "DEBUG",
                    "formatter": "simple",
                    "stream": "ext://sys.stdout"
                },

                "file": {
                    "class": "logging.handlers.RotatingFileHandler",
                    "level": "DEBUG",
                    "formatter": "simple",
                    "filename": self.debug_log,
                    'mode': 'w+',
                    "maxBytes": 1024 * 1024 * 10,  # 10 MB
                    "backupCount": 5,
                    "encoding": "utf-8"
                }
            },
            "loggers": {
                "console_logger": {
                    "level": "DEBUG",
                    "handlers": ["console"],
                    "propagate": "no"
                },

                "debug_logger": {
                    "level": "DEBUG",
                    "handlers": ["console", "file"],
                    "propagate": "no"
                }
            }
        }
        return config

    def debug_logger(self):
        """使用 debug_logger：同时向控制台和log日志中输出日志"""

        config = self._conf()
        logging.config.dictConfig(config)
        logger = logging.getLogger('debug_logger')
        return logger

